import { DefaultObj } from './config'
/** 数组去重
 * @param target 愿数组 [{name:'章三',age: 12},{name:'李四',age: 12}, 1,1]
 * @param { attr = '' } 数组对象中需要校验唯一的属性 age
 * @returns 返回最终过滤重复的数据 [{name:'章三',age: 12},1]
 */
const ArrayObjectDeDuplication = (
  target: string[] | number[] | DefaultObj[],
  attr: string = ''
) => {
  if (!attr) {
    return [...new Set(target as any)]
  }
  const map = new Map()
  for (const item of target) {
    const bol = typeof item == 'string' || typeof item == 'number'
    if (!item) {
      !map.has(item) && map.set(item, item)
    } else if (!map.has(item[attr])) {
      map.set(bol ? item : item[attr], item)
    }
  }
  return [...map.values()]
}
/**
 * 数组去重，需处理数组中对象中多个属性的重复
 * @param target 原数组  愿数组 [{name:'章三',age: 12},{name:'李四',age: 12}, 1,1]
 * @param obj 需要校验唯一性的属性对象 ['age']
 * @returns 最终过滤完的新数组 [{name:'章三',age: 12},1]
 */
const ArrayOnly = (target: any[], obj: string[] = []) => {
  let arr = target
  if (!obj.length) {
    arr = ArrayObjectDeDuplication(arr, '')
  } else {
    obj.map((key) => {
      arr = ArrayObjectDeDuplication(arr, key)
    })
  }
  return arr
}
/* ArrayOnly 功能等同于
  console.log(_.uniqWith(target, _.isEqual))
  ps: 可通过数组交集判定新老数组重复的值 lodash 的 intersection/intersectionBy
 */

export default ArrayOnly
